<template>
	<view class="wrap">
		<!-- 账户栏 -->
		<view v-if="isLogin" class="top-0">
			<u-row gutter="12">
				<!-- 头像 -->
				<u-col span="4">
					<view class="demo-layout bg-purple">
						<view class="avatar">
							<image id="avatarUrl" :src="avatarUrl" mode="aspectFill"
								:style="{ width: '100px', height: '100px', borderRadius: '50%', overflow: 'hidden' }">
							</image>
						</view>
					</view>
				</u-col>
				<!-- 账户信息 -->
				<u-col span="4">
					<view class="demo-layout bg-purple-light">
						<view class="username">
							<p id="nickName" class="fontOne">{{nickName}}</p>
						</view>
					</view>
				</u-col>
				<!-- 验证手机号 -->
			<!-- 	<u-col span="4">
					<view class="demo-layout bg-purple-light">
						<view class="isPhone" @click="toPhone()">
							设置
						</view>
					</view>
				</u-col> -->
			</u-row>
		</view>
		<view v-else class="top-0">
			<u-row gutter="12">
				<!-- 头像 -->
				<u-col span="4">
					<view class="demo-layout bg-purple">
						<view class="avatar">
							<u-avatar mode="square" size="200rpx"></u-avatar>
						</view>
					</view>
				</u-col>
				<!-- 账户信息 -->
				<u-col span="8">
					<view class="demo-layout bg-purple-light">
						<!-- <view @click="getEquipment()"> -->
						<view>
					  <!-- 获取用户手机号的授权按钮 -->
					    <button class="login-button"  open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">登录</button>
						</view>
					</view>
				</u-col>
			</u-row>
		</view>
		<u-row>
			<!-- 通知 -->
			<view class="notice">
				<u-notice-bar type="primary" bg-color="white" color="rgb(39, 57, 101)" mode="horizontal"
					:is-circular="true" :text="list" border-radius="100rpx" class="notice1"></u-notice-bar>
			</view>
		</u-row>
		<!-- 功能栏 -->
		<view class="between-0">
			<u-row gutter="16">
				<u-col span="12">
					<u-grid :col="3">
						<u-grid-item @click="toMyLike()" class="like">
							<image class="mylike" :src="'../../static/icon/我的点赞.png'"></image>
							<view class="grid-text">我的点赞</view>
						</u-grid-item>
						<u-grid-item @click="toMyCollection()">
							<image class="mylike" :src="'../../static/icon/我的收藏.png'"></image>
							<view class="grid-text">我的收藏</view>
						</u-grid-item>
						<u-grid-item @click="toMyBooking()">
							<image class="mylike" :src="'../../static/icon/我的预约2.png'"></image>
							<view class="grid-text">我的预约</view>
						</u-grid-item>
					</u-grid>
				</u-col>
			</u-row>
			<u-row gutter="16">
				<u-col span="12">
					<u-grid :col="3">
					<!-- 	<u-grid-item @click="toShare()" class="like">
							<image class="mylike" :src="'../../static/icon/分享1.png'"></image>
							<view class="grid-text">分享作品</view>
						</u-grid-item>
						<u-grid-item @click="toUserSharing()" class="like">
							<image class="mylike" :src="'../../static/icon/我的分享.png'"></image>
							<view class="grid-text">我的分享</view>
						</u-grid-item> -->
						<u-grid-item  @click="toNews()" class="like">
							<image class="mylike" :src="'../../static/icon/社区活动.png'"></image>
							<view class="grid-text">活动中心</view>
						</u-grid-item>
						<!-- <u-grid-item @click="toNews()" class="like">
							<image class="mylike" :src="'../../static/icon/消息.png'"></image>
							<view class="grid-text">消息</view>
						</u-grid-item> -->
						<u-grid-item v-if="isMerchant && isLogin" @click="timeRange()" class="like">
							<image class="mylike" :src="'../../static/icon/营业时间.png'"></image>
							<view class="grid-text">营业时间</view>
						</u-grid-item>
					</u-grid>
				</u-col>
			</u-row>
		</view>
		<!-- 页脚栏 -->
		<view class="foot1">
			<u-cell-group>
				<!-- 	<u-cell title="联系客服" @click="contact()" v-if="!isMerchant" :isLink="true" arrow-direction="right"
					size='large'>
				</u-cell> -->
				<!-- <u-cell title="活动中心" url="/pages/activity/index" :isLink="true" arrow-direction="right"
					size='large'></u-cell> -->
					<u-cell title="关于我们" url="/pages/my/about/about" :isLink="true" arrow-direction="right"
					size='large'></u-cell>
				<u-cell title="退出登录" @click="loginOut()" :isLink="true" arrow-direction="right" size='large'></u-cell>
			</u-cell-group>
		</view>
		<!-- 	<tab-bar :current="3"></tab-bar> -->
		<!-- 弹出框 -->
		<view>
			<u-popup :show="show" mode="bottom" @close="close">
				<view class="LoginAlert">
					<p class="AlertText">你未登录，请先登录</p>
					<view class="AlertButton">
						<u-button type="success" text="登录" @click="getEquipment()"></u-button>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>
<script>
	import request from '@/util/request';
	export default {
		data() {
			return {
				triggered: false,
				list: "欢迎到本店参观",
				isLogin: false,
				userInfo: {},
				show: false,
				avatarUrl: "../../static/icon/默认头像.jpg",
				nickName: "手作大师",
				loginUser: {
					avatarUrl: "../../static/icon/默认头像.jpg",
					nickName: "手作大师",
				},
				deviceId: 0,
				isMerchant: false, // 是否是商家
				isMerchantPhone: '',
			}
		}, 
		onShow: function() {
			// 每次页面显示时重新加载数据
			//this.getPhone()
			console.log("...onShow")
			//检查用户是否授权过，如果授权过直接登录，否则需要用户授权
			this.checkLogin()
		},
		onLoad() {
			//console.log("...onLoad")
			//this.login()
			//this.checKLogin()
			//this.checkLogin()
		},
		methods: {
			getLoginUserInfo(){
				this.$myRequest({
					url: '/app/userInfo', // 你的后端解密接口
					method: 'get'
				}).then(res =>{
					uni.setStorageSync("appUser",res.appUser)
				})	
			},
			//判断是否登录
			checkLogin() {
				this.isLogin = uni.getStorageSync('isLogin');
				if(!this.isLogin){
					uni.login({
						provider: 'weixin',
						success: (res) => {
								this.$myRequest({
									url: '/app/checkLogin', // 你的后端解密接口
									method: 'get',
									data: {
										code:res.code
									},
								}).then(res =>{
									console.log(res)
									if(res.token){
										console.log(res)
										this.isLogin = true
										uni.setStorageSync('token',res.token)
										//uni.setStorageSync('appUser',res.appUser)
										uni.setStorage({
											key: 'isLogin',
											data: true
										})
										this.getLoginUserInfo();
									}
								})
						},
						fail: (err) => {
							console.error('微信登录失败', err);
						}
					});
				}
			},
			getPhoneNumber(event) {
				// 判断用户是否授权成功
				if (event.detail.errMsg === 'getPhoneNumber:ok') {
					const encryptedData = event.detail.encryptedData;
					const iv = event.detail.iv;
						console.log("获取code'")
					uni.login({
						provider: 'weixin',
						success: (res) => {
							if (res.code) {
								console.log(res)
								this.getUserPhoneNumber(res.code,encryptedData,iv);
							}
						},
						fail: (err) => {
							console.error('微信登录失败', err);
						}
					});
				} else if (event.detail.errMsg === 'getPhoneNumber:fail no permission') {
					  uni.showModal({
						title: '提示',
						content: '您拒绝了手机号授权，无法继续操作。请在设置中开启权限或重新授权。',
						success(res) {
						  if (res.confirm) {
							// 引导用户到设置页面，告诉用户如何手动授权
							uni.openSetting({
							  success: (settingRes) => {
								if (settingRes.authSetting['scope.phoneNumber']) {
								  // 用户已授权
								  console.log('用户已授权手机号');
								} else {
								  console.log('用户未授权手机号');
								}
							  }
							});
						  }
						}
					  });
				}else {
					console.log('用户拒绝授权或发生错误');
				}
			},
			// 调用后端接口解密手机号数据
			getUserPhoneNumber(code,encryptedData, iv) {
				this.$myRequest({
					url: '/app/wxLogin', // 你的后端解密接口
					method: 'get',
					data: {
						code:code,
						encryptedData: encryptedData,
						iv: iv
					},
				}).then(res =>{
					uni.setStorageSync('token',res.token)
					uni.setStorageSync('appUser',res.appUser)
					uni.showToast({
							title: '登录成功',
							icon: 'success',
							duration: 2000 // 持续时间，单位为毫秒
						});
					this.isLogin = true
					uni.setStorage({
						key: 'isLogin',
						data: true
					})
					//console.log("手机号："+res)
				})
			},
		     // 请求后端获取 openid 和 session_key
		    getSessionKey(code) {
				this.$myRequest({
				 	url: '/app/wxLogin',
				 	method: 'GET',
					 data: { code },
				}).then(res =>{
					const { openid, session_key } = res.data;
					this.openid = openid;
					// 调用后端接口解密数据，获取手机号
					this.getUserPhoneNumber(session_key,encryptedData, iv);
					console.log('获取到的 openid:', openid);
				})
		    },
		    // 获取用户信息
		    getUserProfile() {
				 wx.getUserProfile({
				   desc: '用于展示用户信息',  // 描述用途，这个是必填项
				   success: (res) => {
				     console.log(res.userInfo); // 用户信息，包括头像、昵称
				     const userInfo = res.userInfo;
				     const avatarUrl = userInfo.avatarUrl; // 用户头像链接
				     const nickName = userInfo.nickName; // 用户昵称
				     this.avatarUrl = avatarUrl
					 this.isLogin = true
					 // 你可以在这里将头像和昵称存储到 data 或其他地方
				   },
				   fail: (err) => {
				     console.error('获取用户信息失败', err);
				   }
				 });
		       // uni.getUserProfile({
		       //   desc: '用于完善会员资料',
		       //   success: (res) => {
		       //     const userInfo = res.userInfo;
		       //     console.log('用户信息:', userInfo);
		       //     // 可以将用户信息上传到后端与 openid 绑定
		       //     this.saveUserInfo(userInfo);
		       //   },
		       //   fail: (err) => {
		       //     console.error('用户拒绝授权', err);
		       //   }
		       // });
		     },
		 
		     // 保存用户信息
		     saveUserInfo(userInfo) {
		       uni.request({
		         url: 'https://yourbackend.com/api/saveUserInfo',
		         method: 'POST',
		         data: { openid: this.openid, userInfo },
		         success: (res) => {
		           console.log('用户信息保存成功', res);
		         },
		         fail: (err) => {
		           console.error('保存用户信息失败', err);
		         }
		       });
		     },
			login1() {
				wx.login({
					success: res => {
						const code = res.code; //
						this.getPhone()
					}
				})
			},
			//登录
			getEquipment() {
				// 提取设备号（唯一标识符） 
				const userId = uni.getSystemInfoSync().deviceId;
				// 输出设备号 
				// wx.getUserProfile({
				// 	desc: '获取你的头像和昵称',
				// 	success: (ress) => {
				request({
					url: '/users/login',
					method: 'post',
					data: {
						userId: userId,
					}
				}).then(res => {
					this.nickName = res.data.nickName
					console.log("res.data" + JSON.stringify(res.data))
					if (res.data.avatarUrl != null) {
						this.avatarUrl = this.$baseUrl + res.data.avatarUrl
					}
					uni.setStorageSync("loginUser", res.data)
					uni.showToast({
						title: '登录成功',
						icon: 'success',
						duration: 2000 // 持续时间，单位为毫秒
					});
				})
				uni.setStorage({
					key: 'isLogin',
					data: true
				})
				uni.reLaunch({
					url: "/pages/my/index"
				})
				//},
				// 	fail: (err) => {
				// 	}
				// });
			},
			getUserPhone() {
				if (this.isLogin) {
					request({
						url: '/users/getUserById',
						method: 'get',
						data: {
							userId: this.deviceId
						}
					}).then(res => {
						this.name = res.data.nickName
						this.isMerchantPhone = res.data.phone
					})
				}
			},
			getPhone() {
				//获取电话
				this.getUserPhone();
				request({
					url: '/about/query',
					method: 'GET',
				}).then(res => {
					this.aboutInfo = res;
					this.merchantPhone = this.aboutInfo.data.phone
					this.phone = this.isMerchantPhone
					this.isMerchant = this.isMerchantPhone === this.aboutInfo.data.phone; //商家
				})
			},
		
			// 联系客服
			contact() {
				const isLogin = this.isLogin;
				if (isLogin) {
					uni.navigateTo({
						url: `/pages/user/index?avatarUrl=${this.avatarUrl}`,
					});
				} else {
					this.show = true
				}

			},
			//退出登录
			loginOut() {
				const isLogin = uni.getStorageSync('isLogin');
				if (isLogin) {
					uni.removeStorageSync("loginUser")
					uni.removeStorage({
						key: 'isLogin'
					});
					uni.removeStorageSync("aaUser")
					uni.reLaunch({
						url: "/pages/my/index"
					})
				}
			},
			close() {
				this.show = false
				// console.log('close');
			},
			//跳转我的点赞
			toMyLike() {
				const isLogin = this.isLogin;
				if (isLogin) {
					uni.navigateTo({
						url: "/pages/my/mylike/index"
					})
				} else {
					this.show = true
				}
			},
			//跳转我的收藏
			toMyCollection() {
				const isLogin = this.isLogin;
				if (isLogin) {
					uni.navigateTo({
						url: "/pages/my/mycollection/index"
					})
				} else {
					this.show = true
				}
			},
			// 跳转分享页面
			toShare() {
				if (this.isLogin) {
					uni.navigateTo({
						url: `/pages/share/index`
					})
				} else {
					this.show = true
				}
			},
			// 去往消息列表
			toNews() {
				uni.navigateTo({
					url:`/pages/activity/index`
					// url: `/pages/service/index?loginUserId=${this.isMerchantPhone}&avatarUrl=${this.avatarUrl}`,
				})

			},  
			//跳转我的预约
			toMyBooking() {
				const isLogin = this.isLogin;
				if (isLogin) {
					uni.navigateTo({
						url: `/pages/my/booking/booking`
					})
				} else {
					this.show = true
				}
			},

			//跳转修改信息页面
			toPhone() {
				uni.navigateTo({
					url: "/pages/my/updateMy/index"
				})
			},

			//跳转到设置营业时间页面
			timeRange() {
				uni.navigateTo({
					url: "/pages/my/timerange/index"
				})
			},
			//跳转我的分享
			toUserSharing() {
				if (this.isLogin) {
					uni.navigateTo({
						url: `/pages/share/usersharing/index`
					})
				} else {
					this.show = true
				}
			}
		}
	}
</script>
<style>
	/* 设置按钮样式 */
	  .login-button {
	    width: 100px;               /* 设置按钮的宽度 */
	    height: 50px;               /* 设置按钮的高度 */
	    background-color: #007aff;  /* 设置按钮背景色 */
	    color: white;               /* 设置按钮文字颜色 */
	    font-size: 16px;            /* 设置按钮字体大小 */
	    border-radius: 25px;        /* 设置按钮圆角 */
	    border: none;               /* 去掉按钮的默认边框 */
	    text-align: center;         /* 设置按钮文字居中 */
	    line-height: 50px;          /* 垂直居中文本 */
	    cursor: pointer;            /* 鼠标悬停时显示为手指状 */
	  }
	
	  .login-button:hover {
	    opacity: 0.8;               /* 悬停时稍微透明 */
	  }
	/* 账户栏 */
	.top-0 {
		width: 95%;
		height: 250rpx;
		margin: auto;
		margin-top: 50rpx;
		background-color: white;
	}

	/* 修改个人信息 */
	.isPhone {
		width: 100%;
		height: 80rpx;
		/* 		background-color: rgb(27, 250, 42); */
		line-height: 80rpx;
		text-align: center;
		border-radius: 50rpx 0 0 50rpx;
		font-size: 24rpx;
	}

	.avatar {
		width: 200rpx;
		height: 200rpx;
	}

	/* 内部账户栏样式 */
	.demo-layout {
		margin-top: 25rpx;
		margin-left: 50rpx;
	}

	/* 通知栏 */
	.notice {
		width: 95%;
		margin: auto;
		margin-top: 50rpx;
	}

	/* 中间块 */
	.between-0 {
		width: 95%;
		height: auto;
		margin: auto;
		margin-top: 80rpx;
		padding-bottom: 50rpx;
		/* background-color: rgb(255, 255, 240); */
		background-color: white;

	}

	/* 点赞收藏图标 */
	.mylike {
		width: 80rpx;
		height: 80rpx;
		margin-top: 50rpx;
	}

	/* 图标文字 */
	.grid-text {
		margin-top: 5rpx;
	}

	.foot1 {
		width: 95%;
		height: auto;
		margin: auto;
		margin-top: 60rpx;
		/* background-color: rgb(255, 255, 240); */
		background-color: white;
	}

	/* 弹出框 */
	.LoginAlert {
		width: 95%;
		height: 200rpx;
		text-align: center;
		font-size: 30rpx;
	}

	/* 弹出框按钮 */
	.AlertButton {
		width: 80%;
		margin: auto;
	}

	/* 弹出框文字 */
	.AlertText {
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}
</style>